﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Text;


namespace EmployeeCheckIn
{
    public partial class RegisterPage : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            Lbempty();
            if (Session["User"] != null && Session["Pass"] != null)
            {
                string user = Session["User"].ToString();
                string pass = Session["Pass"].ToString();

                int i;
                if (!IsPostBack)
                {
                    i = GetID();
                    string idGen = string.Format("SMMMS{0:000}", i);
                    hdf_EmpID.Value = i.ToString();
                    txtEmp_code.Text = idGen;
                    TXTempty();
                }                
            }
            else
            {
                Response.Redirect("Default.aspx");
            }                     
            
        }
        private void TXTempty()
        {
            txtFirstName.Text = "";
            txtLastname.Text = "";
            txtStartdate.Text = "";
            txtBirthDate.Text = "";
            txtAddress.Text = "";
            txtIdCard.Text = "";
            txtPostId.Text = "";
            txtTel.Text = "";
        }
        private void Lbempty()
        {
            lbEmpCode.Visible = false;
            lbStdate.Visible = false;
            lbUpsucsess.Visible = true;
            lbWarnBirth.Visible = false;
            lbWarnIDc.Visible=false;
            lbWarnLastname.Visible = false;
            lbWarnName.Visible = false;
            lbWarnPost.Visible = false;
            lbWarnPhone.Visible = false;
        }
        public DateTime ConvestToDate(string s)
        {
            int day=1;
            int mount=1;
            int years=1111;
            try
            {
                string[] stemp = s.Split('/');
                day = Convert.ToInt32(stemp[0]);
                mount = Convert.ToInt32(stemp[1]);
                years = Convert.ToInt32(stemp[2]);
                if (years > 2300)
                {
                    years = years - 543;
                }
                return new DateTime(years, mount, day);
            }
            catch (Exception)
            {
                return DateTime.Now;
                //lbStdate.Visible = true;
                //lbStdate.Text = "*รูปแบบ วว/ดด/ปปปป";
                //lbStdate.Visible = true;
                //lbStdate.Text = "*รูปแบบ วว/ดด/ปปปป";
            }
            
        }
        public bool CheckConvestToDate(string s)
        {
            int day;
            int mount;
            int years;
            bool resault = false;
            try
            {
                string[] stemp = s.Split('/');
                day = Convert.ToInt32(stemp[0]);
                mount = Convert.ToInt32(stemp[1]);
                years = Convert.ToInt32(stemp[2]);
                if (years > 2300)
                {
                    years = years - 543;
                }
                return resault = true;
            }
            catch (Exception)
            {

                resault = false;
            }
            return resault;

        }
      
        public bool checknumber(string s)
        {
            //bool result = false;
            //string Str = s.Trim();
            //double Num;
            //bool isNum = double.TryParse(Str, out Num);
            //if (isNum)
            //{ 
            //    result = true; 
            //}
            //return result;

            bool result = false;
            try
            {
                Convert.ToDouble(s);
                result = true;
            }
            catch (Exception)
            {
                result = false;

            }
            return result;
        }      
        private int GetID()
        {
            int id;
            string sqltext = @"SELECT ISNULL (MAX(EMP_ID),0)
                                from EMPLOYEE";
            SqlCommand sqlcomm = new SqlCommand();
            SqlConnection sqlconn = new SqlConnection("Server=202.44.52.248;Database=DB_Personal;User Id=personal;Password=1234;");
            sqlcomm.Connection = sqlconn;
            sqlcomm.CommandType = System.Data.CommandType.Text;
            sqlcomm.CommandText = sqltext;
            try
            {
                sqlcomm.Connection.Open();
                id = (int)sqlcomm.ExecuteScalar() + 1;
            }
            catch (Exception)
            {

                sqlcomm.Connection.Close();
                sqlcomm.Connection.Dispose();
                throw;
            }
            sqlcomm.Connection.Close();
            sqlcomm.Connection.Dispose();
            return id;
        }
        private int chkID(int memberId)
        {
            int idchk;
            string sqltext = @"SELECT ISNULL (MAX(EMP_ID),0)
                                from EMPLOYEE WHERE EMP_ID =" + memberId + "";
            SqlCommand sqlcomm = new SqlCommand();
            SqlConnection sqlconn = new SqlConnection("Server=202.44.52.248;Database=DB_Personal;User Id=personal;Password=1234;");
            sqlcomm.Connection = sqlconn;
            sqlcomm.CommandType = System.Data.CommandType.Text;
            sqlcomm.CommandText = sqltext;
            try
            {
                sqlcomm.Connection.Open();
                idchk = (int)sqlcomm.ExecuteScalar();
            }
            catch (Exception)
            {

                sqlcomm.Connection.Close();
                sqlcomm.Connection.Dispose();
                throw;
            }
            sqlcomm.Connection.Close();
            sqlcomm.Connection.Dispose();
            return idchk;
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            if (Session["User"] != null && Session["Pass"] != null)
            {
                 TXTempty();
                 Response.Redirect("RegisterPage.aspx");
            //cancle กลับหน้า ของแอดมิน
            }
            else
            {
                //กลับหน้า defal
                Response.Redirect("Default.aspx");
            }
            
        }

        protected void btRegister_Click1(object sender, EventArgs e)
        {
            Lbempty();
            if (Session["User"] != null && Session["Pass"] != null)
            {
                InSertData intsert = new InSertData();
                EmpEntity emp = new EmpEntity();
                StringBuilder sb = new StringBuilder();


                bool result = false;
                bool submit = true;
                emp.ID = Convert.ToInt32(hdf_EmpID.Value);
                emp.EmpId = txtEmp_code.Text;
                emp.Prefix = Convert.ToInt32(rblPrefix.SelectedValue);
                emp.FirstName = txtFirstName.Text;
                emp.LastName = txtLastname.Text;
                emp.Position = Convert.ToInt32(ddlPosition.SelectedValue);
                if (CheckConvestToDate(txtBirthDate.Text) == false)
                {
                    //lbWarnBirth.Visible = true;
                    //lbWarnBirth.Text = "*รูปแบบ วว/ดด/ปปปป";
                    //result = true;
                    //submit = false;
                }
                if (CheckConvestToDate(txtStartdate.Text) == false)
                {
                    //lbStdate.Visible = true;
                    //lbStdate.Text = "*รูปแบบ วว/ดด/ปปปป";
                    //result = true;
                    //submit = false;
                }
                DateTime dtmBirth = ConvestToDate(txtBirthDate.Text);
                DateTime dtmStart = ConvestToDate(txtStartdate.Text);
                emp.DateBirth = dtmBirth;
                emp.DateStart = dtmStart;
                emp.CardID = txtIdCard.Text;
                emp.Address = txtAddress.Text;
                emp.City = Convert.ToInt32(ddlProvince.SelectedValue);
                emp.PostID = txtPostId.Text;
                emp.Phone = txtTel.Text;
                emp.status = Convert.ToInt32(ddlStatus.SelectedValue);
                if (chkID(emp.ID) > 0)
                {
                    lbEmpCode.Visible = true;
                    lbEmpCode.Text = "ขออภัยรหัสซ้ำ";
                    sb.Append("<script language='javascript' type = 'text/javascript'>");
                    sb.Append("alert('ขออภัยรหัสซ้ำ')");
                    sb.Append("</script>");
                    Response.Write(sb.ToString());
                    result = true;
                    submit = false;
                    Response.Redirect("RegisterPage.aspx");

                }
                if (txtFirstName.Text == "")
                {
                    lbWarnName.Visible = true;
                    lbWarnName.Text = "*กรุณากรอกชื่อ";
                    txtFirstName.Focus();
                    result = true;
                    submit = false;
                }
                //if (txtTel.Text=="")
                //{
                //    lbWarnPhone.Visible = true;
                //    lbWarnPhone.Text = "*กรุณากรอกเบอร์โทรศัพท์";
                //    result = true;
                //    submit = false;
                //}
                if (txtLastname.Text == "")
                {
                    lbWarnLastname.Visible = true;
                    lbWarnLastname.Text = "*กรุณากรอกนามสกุล";
                    result = true;
                    submit = false;
                }
                //if (txtPostId.Text == "")
                //{
                //    lbWarnPost.Visible = true;
                //    lbWarnPost.Text = "*กรุณากรอกรหัสไปรษณีย์";
                //    result = true;
                //    submit = false;
                //}
                if ((checknumber(txtIdCard.Text) == false && txtIdCard.Text != ""))
                {
                    lbWarnIDc.Visible = true;
                    lbWarnIDc.Text = "*กรุณากรอกข้อมูล เป็นตัวเลข";
                    result = true;
                    submit = false;
                }
                if (result == true && submit == false)
                {
                    return;
                }
                if (IsPostBack)
                {

                    String fileExtension = "";
                    Boolean fileOK = false;
                    String path = Server.MapPath("~/Immages/");
                    if (upfPicture.HasFile)
                    {
                        fileExtension = System.IO.Path.GetExtension(upfPicture.FileName);
                        String[] allowedExtensions = { ".gif", ".png", ".jpeg", ".jpg", ".GIF", ".PNG", ".JPG" };
                        for (int j = 0; j < allowedExtensions.Length; j++)
                        {
                            if (fileExtension == allowedExtensions[j])
                            {
                                fileOK = true;
                            }
                        }
                    }
                    if (!(upfPicture.HasFile))
                    {
                        fileOK = true;
                    }

                    if (fileOK)
                    {
                        try
                        {
                            emp.EmpPic = "~/Immages/" + upfPicture.FileName;
                            upfPicture.SaveAs(path + upfPicture.FileName);
                            lbUpsucsess.Text = "File uploaded!";
                        }
                        catch (Exception)
                        {
                            result = true;
                            emp.EmpPic = "~/images/logo_smmms.png";
                            submit = true;
                            
                        }
                    }
                    else
                    {
                        result = true;
                        lbUpsucsess.Text = "ไม่รองรับไฟล์ชนิดนี้";
                        submit = false;
                    }
                }
                if (submit == true)
                {
                    
                    Response.Write(sb.ToString());
                    intsert.Insertss(emp);
                    Response.Write("<script>alert('บันทึกข้อมูลเรียบร้อยแล้ว!'); window.location='ShowList_Empoyee.aspx';</script>");
                }
            }
            else
            {
                Response.Redirect("Default.aspx");
            }
                
                
         }

        protected void Button2_Click(object sender, EventArgs e)
        {
            Response.Redirect("ShowList_Empoyee.aspx");
        }
     }
  }
